package com.cr.dataprotect.interceptor;


import com.cr.dataprotect.bean.ProviderConfigBean;
import com.cr.dataprotect.manage.DesensitizationManage;
import com.cr.dataprotect.provider.AbstractProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/**
 * 脱敏参数拦截（用于解决编辑时前端传来脱敏后的数据）
 *
 * @author ChenRu1
 * @Description
 * @Date 16:04 2023/12/07
 **/
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Slf4j
@Component
@Order(1)
public class StatementInterceptor extends AbstractProvider implements Interceptor {
    @Autowired
    private DesensitizationManage desensitizationManage;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!super.hasProvider()) {
            //如果没配置敏感字段，不需要处理
            return invocation.proceed();
        }

        ProviderConfigBean providerConfigBean = super.loadAllFieldConfig();
        if (MapUtils.isNotEmpty(providerConfigBean.getDesensitization())) {
            desensitizationManage.desensitizationParameter(invocation, providerConfigBean.getDesensitization());
        }


        return invocation.proceed();
    }
}